$(function() {
//Pagination.
    $page.init();
    $product.init();
    //////
    $('input.date').datepicker();
    $('#dialog_upload_image').dialog({
        autoOpen: false,
        width: 300,
        height: 150,
        modal: true,
        buttons: {
            Upload: function() {
                $('#form_image_product').submit();
            },
            Cancel: function() {

                $product.resetUploadImgInput();
                $(this).dialog('close');
            }
        }
    });
    $('#dialog_product_detail').dialog({
        autoOpen: false,
        modal: true
    });
    $('input.add').click(function() {
        $('#dialog_add').dialog("open");
    });
    $('input#product_image_btn').click(function() {
        $('#dialog_upload_image').dialog('open');
    });
    //Tooltip
    $('#username, #email, #pass2').tooltip();
    //Vertical tabs.
    $("#dialog_add").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
    $("#dialog_add li").removeClass("ui-corner-top").addClass("ui-corner-left");
    //Add more input link to product detail section....
    $('#more_input').click(function() {
        $('.product-links').append($('.product-links .input-link').clone()[0]);
    });
    //View detail product.
    $('table.table-content tr.even, table.table-content tr.odd').click(function(event) {
        if (event.target.nodeName != 'A') {
            $('#dialog_product_detail').dialog('open');
        }
    });
    //Show popup edit.
    $('tr td a.edit').live('click', (function(event) {
        event.preventDefault();
        $('#dialog_add').dialog("open");
    }));
    //product category tree view 
    $("#product_category_tree").treeview();
});
var $tut = {
    token_name: 'token_name',
    token_value: 'token_value',
    ajax: function($option) {
        $option.data.tut_token = $('#' + this.token_value).val();
        $.ajax($option);
    }
};
var $product = {
    fields: {
        name: 'product_name',
        order: 'product_order',
        level: "product_level",
        language: 'product_language',
        status: 'status',
        featured: 'featured',
        summary: 'product_summary',
        description: 'product_description_slave',
        meta_title: 'product_meta_title',
        meta_keyword: 'product_meta_keyword',
        meta_description: 'product_meta_description',
        meta_robot: 'product_meta_robot',
        image: 'product_image',
        source: 'product_source'
    },
    message: 'error-message',
    actionGetList: '#url_getList',
    init: function() {
        this._load();
        this.getList(0)
                ._renderDescriptionField()
                .uploadImage();
    },
    proccessErrorAdd: function($aError) {
        $product.resetFieldAdd();
//        $aError = eval('(' + $aError + ')');
        for ($error in $aError) {
            $('#' + $product.fields[$error])
                    .after($aError[$error])
                    .css('border', '1px solid red');
            if ($aError[$error] == '') {
                $('#' + $product.fields[$error])
                        .css('border', '');
            }

            $('.' + $product.message)
                    .html($('input#error_message_add').val())
                    .show()
                    .fadeOut(5000, function() {
                $(this).empty();
            });
//            setTimeout(function(){
//                $('.' + $product.message)
//                    .hide()
//                    .empty();
//            },3000);
        }
    },
    resetFieldAdd: function() {
        $('.' + $product.message).empty();
        for ($field in $product.fields) {
            $('#' + $product.fields[$field])
                    .css('border', '');
            $('#' + $product.fields[$field] + '+ div.error').remove('div.error');
        }

//Reset error message of image field.
        $('#' + $product.fields.image + '~ div.error').remove('div.error');
    },
    resetUploadImage: function() {
        $('div.upload-image-product + div.error').remove('div.error');
    },
    resetUploadImgInput: function() {
        $('#form_image_product').get(0).reset();
        $('div.upload-image-product + div.error').remove('div.error');
    },
    resetFormAdd: function() {
        $('#form_add').get(0).reset();
        $product.resetFieldAdd();
        $('#product_image').val('');
        $('#product_image + img').remove('img');
        $('#product_image + br').remove('br');
        //reset error of image field.
        $('#product_image ~ .error').remove('div');
    },
    Add: function() {
        tinyMCE.triggerSave();
        var $option = {
            type: 'post',
            url: $('#form_add').attr('action'),
            dataType: 'json',
            data: $('#form_add').serialize(),
            success: function($response, $status) {
                if ($response.result) {
                    location.reload();
                }
                else {
                    $product.proccessErrorAdd($response.data);
                }

            }
        };
        $.ajax($option);
    },
    uploadImage: function() {
        $('#form_image_product').ajaxForm(
                {
                    success: function($response) {
//                        $response = eval('(' + $response + ')');
                        if ($response.result) {
                            $('div#dialog_upload_image').dialog('close');
                            $product.createImage($response.data);
                            $product.resetUploadImgInput();
                            return true;
                        }

//Reset.
                        $product.resetUploadImage();
                        $('div.upload-image-product').after($response.message);
                    },
                    complete: function($xhr) {
                    }
                });
    },
    createImage: function($object) {
        if ($object == '' || $object == 'undefined') {
            return false;
        }

//        $object = eval('(' + $object + ')');
        $('#product_image').siblings('img').remove('img');
        $('#product_image')
                .val($object.file_name)
                .after("<img src='" + $object.obsolute_path_new_image + "' height='100px' width='100px' alt='' /><br />");
        return true;
    },
    getList: function($offset) {
        var $link = $(this.actionGetList).val() + "/1";
        if ($offset) {
            $link = $(this.actionGetList).val() + "/" + $offset;
        }
        var $option = {
            type: 'post',
            url: $link,
            dataType: 'json',
            data: {},
            success: function($response, $status) {
                if ($response.result) {
                    $product.createList($response.data);
                }
            }
        };

        $tut.ajax($option);

        return this;
    },
    createList: function($productDataList) {
        var $data = $productDataList;
        var $body = $('#body_list');
        $body.empty();

        //Check if no post in table product.
        $('#no_row').remove();
        if (!$data) {
            ///////////////////////////////////Mulitple language here.
            $body.append('<tr id="no_row" class="no-row"><td colspan="11">No product.</td></tr>');
        }

        //Traverse list product
        for (var $i = 0; $i < $data.length; $i++) {
            var $list = '';
            var $row = $data[$i];
            var $productId = null;
            for (var $col in $row) {
                if ($col == 'id') {
                    $productId = $row[$col];
                }

                $list = this.fillData($col, $row[$col], $list);
            }

            $body.append($list);

            if ($i % 2) {
                $('#row_' + $productId).addClass('even');
            }
            else {
                $('#row_' + $productId).addClass('odd');
            }
        }
    },
    fillData: function($col, $data, $list) {
        var $tr = '<tr id="row_{product_id}" class="row">' +
                '<td class="center">' +
                '<input type="checkbox" name="delete[{product_id}]" id="{product_id}" class="product-select" />' +
                '</td>' +
                '<td> {product_name} </td>' +
                '<td class = "center"> {product_stutus}</td>' +
                '<td class = "center"> {product_featured} </td>' +
                '<td> {product_category} </td>' +
                '<td> {product_level} </td>' +
                '<td class = "right"> {product_order} </td>' +
                '<td> {product_date} </td>' +
                '<td> {language} </td>' +
                '<td class="right"> {product_id}</td>' +
                '<td> <a href = "#" class = "edit"> Edit </a></td >' +
                '</tr>';
        if ($list != '') {
            $tr = $list
        }

        switch ($col) {
            case 'id':
                $tr = $tr.replace(/{product_id}/g, $data);
                break;
            case 'name':
                $tr = $tr.replace(/{product_name}/g, $data);
                break;
            case 'category':
                $tr = $tr.replace(/{product_category}/g, $data);
                break;
            case 'level':
                $tr = $tr.replace(/{product_level}/g, $data);
                break;
            case 'order':
                $tr = $tr.replace(/{product_order}/g, $data);
                break;
            case 'language':
                $tr = $tr.replace(/{language}/g, $data);
                break;
            case 'actived':
                $tr = $tr.replace(/{product_stutus}/g, $data);
                break;
            case 'featured':
                $tr = $tr.replace(/{product_featured}/g, $data);
                break;
            default:
                $tr = $tr.replace(/{product_date}/g, $data);
                break;
        }

        return $tr;
    },
    deleteProducts: function() {
        var $class = $('.product-select');
        var $ids = '{';
        for (var $item in $class) {
            if ($class[$item].checked == true) {
                $ids += '"' + $item + '":"' + $class[$item].id + '",';
            }
        }

        $ids = $ids.replace(/,$/g, '') + '}';
        var $option = {
            type: 'post',
            url: 'http://localhost/tuts/index.php/product/admincp/index/delete',
            dataType: 'json',
            data: {product_ids: $ids},
            success: function($response, $status) {
                if ($response.result) {
                    //Close dialog confirm.
                    $('#dialog_del_product').dialog('close');
                    //Get current page.
                    var $cur_page = $('#current_page_product').text();
                    //Get number of item in page for check if that page is item....
                    $('.product-select').length;
                    //Get list product of page.
                    $product.getList($cur_page);
                }
            }
        };

        $tut.ajax($option);

        return this;
    },
    initDialog: function() {
        //Dialog add product...
        $('#dialog_add').dialog({
            autoOpen: false,
            height: 600,
            width: 800,
            modal: true,
            resizable: false,
            draggable: true,
            buttons: {
                Add: function() {
                    $product.Add();
                },
                Reset: function() {
                    $product.resetFormAdd();
                },
                Cancel: function() {
                    $product.resetFormAdd();
                    $(this).dialog("close");
                }
            },
            close: function() {
            }
        });

        //Dialog delete product
        $('#dialog_del_product').dialog({
            autoOpen: false,
            width: 500,
            height: 400,
            modal: true,
            buttons: {
                Ok: function() {
                   $product.deleteProducts();
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        });
        
        return this;
    },
    _load: function() {
        //Check all product...
        $('input#all_product').click(function() {
            $('.product-select').prop('checked', this.checked);
        });

        //Delete multiple user...
        $('input#delete_product').click(function() {
            $('#dialog_del_product').dialog('open');
        });
        
        this.initDialog();
    },
    _renderDescriptionField: function() {
        // Initialize TinyMCE with and listbox
        tinyMCE.init({
            plugins: '-example', // - tells TinyMCE to skip the loading of the plugin
            mode: "exact",
            elements: 'product_description',
            theme: "advanced",
            theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,forecolor,backcolor",
            theme_advanced_buttons3: "hr,removeformat,visualaid,|,sub,sup,|,charmap",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            width: "600",
            height: "500"
        });

        return this;
    },
};
var $page = {
    action: '#url_pagination',
    class: 'page',
    container: '#pagination',
    content: '',
    init: function() {
        this.get(0)
            .pageEvent();
    },
    pageEvent: function() {
        $('.' + this.class).live('click', function($event) {
            $event.preventDefault();
            var $link = $(this).attr('href');
            var $option = {
                type: 'post',
                url: $link,
                dataType: 'json',
                data: {},
                success: function($response, $status) {
                    if ($response.result) {
                        $page.create($response.data)
                                .addClass(this.class);
                        $product.getList($response.other);
                    }
                }
            };
            $tut.ajax($option);
        });
        return this;
    },
    get: function($page_num) {
        var $link = $(this.action).val(); 
        
        if($page_num){
            $link = $(this.action).val() + '/' + $page_num; 
        }
        
        var $option = {
            type: 'post',
            url: $link,
            dataType: 'json',
            data: {},
            success: function($response, $status) {
                if ($response.result) {
                    $page.create($response.data)
                            .addClass(this.class);
                }
            }
        };
        $tut.ajax($option);
        return this;
    },
    create: function($data) {
//        this.content = JSON.parse($data);
        this.content = $data;
        $(this.container).empty()
                .append(this.content);
        return this;
    },
    addClass: function() {
        $(this.container + ' a').addClass(this.class);
        return this;
    }
};